<template>
    <div class="page-header">
        <span class="page-title" style="display: flex;align-items: center;gap: 16px;">
            楼栋管理
            <el-input v-model="searchTerm" clearable placeholder="搜索楼栋..." class="search-input" @input="handleSearch" />
        </span>
    </div>
    <div class="buildings-container">
        <el-row :gutter="16" v-loading="loading">
            <template v-if="filteredBuildings.length > 0">
                <el-col :xs="24" :sm="24" :xl="12" v-for="building in filteredBuildings" :key="building.id">
                    <area-card :name="building.name" :water-meters="getMetersByType(building.name, 1)"
                        :electric-meters="getMetersByType(building.name, 2)"
                        :gas-meters="getMetersByType(building.name, 3)">
                    </area-card>
                </el-col>
            </template>
            <template v-else>
                <el-col :span="24">
                    <el-empty description="暂无楼栋数据" :image-size="200">
                        <template #description>
                            <p>暂无楼栋数据，请检查表计是否已配置楼栋信息</p>
                        </template>
                    </el-empty>
                </el-col>
            </template>
        </el-row>


    </div>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'
import { useCompanyStore } from '@/stores/company'
import { getMeterInfoApi } from '@/api/meter'
import { handleError } from '@/utils/handleError'
import { debounce } from '@/utils/DebounceAndThrottle'
import AreaCard from '@/components/card/BlockCard.vue'

// store
const companyStore = useCompanyStore()

// 本地状态
const loading = ref(false)
const searchTerm = ref('')
const buildingList = ref([])
const filteredBuildings = ref([])



// 表计数据
const metersData = ref([])



// 初始化楼栋列表
const loadBuildingList = () => {
    buildingList.value = []
    updateFilteredBuildings()
}



// 更新筛选后的楼栋列表
const updateFilteredBuildings = () => {
    if (!searchTerm.value) {
        filteredBuildings.value = [...buildingList.value]
    } else {
        filteredBuildings.value = buildingList.value.filter(building =>
            building.name.toLowerCase().includes(searchTerm.value.toLowerCase())
        )
    }
}

// 获取表计数据
const fetchMetersData = async () => {
    loading.value = true
    try {
        const res = await getMeterInfoApi({
            company_id: companyStore.currentCompany.id
        })
        metersData.value = res.data

        // 从表计中提取楼栋
        const cells = new Set()
        metersData.value.forEach(meter => {
            if (meter.cell && meter.cell.trim()) {
                cells.add(meter.cell.trim())
            }
        })

        // 构建楼栋列表
        buildingList.value = Array.from(cells).map(cell => ({
            id: cell.replace(/\s+/g, '_').toLowerCase(),
            name: cell
        }))

        updateFilteredBuildings()
    } catch (error) {
        handleError(error, '获取表计数据失败')
    } finally {
        loading.value = false
    }
}

// 按类型获取楼栋的表计
const getMetersByType = (buildingName, type) => {
    if (!metersData.value || !buildingName) return []
    return metersData.value.filter(meter =>
        meter.cell === buildingName && meter.type === type
    )
}

// 处理搜索
const handleSearch = debounce(() => {
    updateFilteredBuildings()
}, 300)



// 监听搜索词变化
watch(searchTerm, () => {
    updateFilteredBuildings()
})

// 监听公司变化
watch(() => companyStore.currentCompany?.id, async (newVal) => {
    if (newVal) {
        await fetchMetersData()
    }
}, { immediate: true })

// 组件挂载时加载数据
onMounted(() => {
    if (companyStore.currentCompany?.id) {
        fetchMetersData()
    }
})
</script>

<style scoped>
.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
}

.page-title {
    font-size: 18px;
    font-weight: bold;
    display: flex;
    align-items: center;
    gap: 16px;
}

.buildings-container {
    position: relative;
}

.search-input {
    width: 200px;
}
</style>